<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        isNeedSelection
        :btnList="btnList"
        :total="totalNum"
        v-model="searchParams"
        :searchShowList="searchShowList"
        :tableColumn="tableColumn"
        requestName="searchHandle"
        :tableData="tableData"
        @rowDelete="operateHandle($event, 'rowDelete')"
        @add="operateHandle($event, 'add')"
        @rowEdit="operateHandle($event, 'rowEdit')"
        @delete="operateHandle($event, 'delete')"
        @reset="operateHandle($event, 'reset')"
        @roleSet="operateHandle($event, 'roleSet')"
        @rowGrant="operateHandle($event, 'rowGrant')"
      />
    </div>
    <TrEditPopup
      v-model="isShowEdit"
      :title="checkTitle"
      :width="checkWidth"
      :valueObj.sync="formObj"
      :formData="formData"
      :list="checkList"
      @close="isShowEdit = false"
      @confrim="confirmHandle"
    >
    </TrEditPopup>
    <TrDetail
      v-model="isShowDetailPopup"
      :leftList="detailList"
      statusModel="hidden"
      :detailData="detailData"
    />
    <TrLayout
      v-model="isShowGrantPopup"
      title="组织架构"
      :width="960"
      :footerTop="8"
      @close="closePopupHandle"
      @confrim="confirmFactHandle"
    >
      <TrTable
        ref="factTable"
        isNeedSelection
        v-model="grantSearchParams"
        isPopup
        :total="grantTotal"
        :tableColumn="grantColumn"
        requestName="getGrantDataHandle"
        :tableData="grantTableData"
        :checkedList.sync="checkedList"
        @change-switch="changeSwitchHandle"
      >
      </TrTable>
    </TrLayout>
  </div>
</template>

<script>
import { findByProperty } from "@/utils/util";
import { getDeptLazyTree } from "@/api/system/dept";
import { getRoleList } from "@/api/system/role";
import { getTreeList } from "@/api/baseCode/organizationalStructure";
import {
  getList,
  add,
  remove,
  resetPassword,
  grant,
  savaFact,
} from "@/api/system/user";
import TrEditPopup from "@/components/Tr-edit/Tr-edit-popup.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrLayout from "@/components/Tr-layout/Tr-layout.vue";
import md5 from "js-md5";
export default {
  name: "UserBox",
  components: {
    TrLayout,
    TrEditPopup,
    TrTable,
    TrDetail,
  },
  computed: {
    checkWidth() {
      return this.currentHandle == "roleSet" ? 480 : 960;
    },
    checkTitle() {
      return this.currentHandle == "add"
        ? "新增用户"
        : this.currentHandle == "rowEdit"
        ? "编辑用户"
        : "用户角色配置";
    },
    checkList() {
      let fList = this.popupList.filter((item) => {
        return item.id != "password" && item.id != "password2";
      });
      let roleList = this.popupList.filter((item) => {
        return item.id == "roleIdList";
      });
      return this.currentHandle == "add"
        ? this.popupList
        : this.currentHandle == "rowEdit"
        ? fList
        : roleList;
    },
    ids() {
      let ids = [];
      this.$refs.trTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    factIds() {
      return this.$refs.factTable.selectionList.map((item) => item.id);
    },
  },
  watch: {
    currentHandle(newVal) {
      const column = findByProperty(this.popupList, "id", "roleIdList");
      column.width = newVal == "roleSet" ? 100 : 50;
    },
  },
  data() {
    return {
      grantSearchParams: {
        orgLevelCode: "FACTORY",
        current: 1,
        size: 10,
      },
      grantTableData: [],
      grantTotal: 0,
      grantColumn: [
        {
          type: "switch",
          label: "默认组织架构",
          value: "isDefault",
        },
        {
          type: "text",
          label: "组织代码",
          value: "orgCode",
        },
        {
          type: "text",
          label: "组织名称",
          value: "orgName",
        },
        {
          type: "text",
          label: "组织描述",
          value: "orgDesc",
        },
      ],
      isShowGrantPopup: false,
      detailData: {},
      isShowDetailPopup: false,
      detailList: [
        {
          type: "text",
          label: "用户信息",
          list: [
            {
              text: "所属租户",
              id: "tenantName",
              width: 50,
            },
            {
              text: "登录账号",
              id: "account",
              width: 50,
            },
            {
              text: "用户昵称",
              id: "name",
              width: 50,
            },
            {
              text: "用户姓名",
              id: "realName",
              width: 50,
            },
            {
              text: "所属角色",
              id: "roleName",
              width: 50,
            },
            {
              text: "所属部门",
              id: "deptName",
              width: 50,
            },
            {
              text: "手机号码",
              id: "phone",
              width: 50,
            },
            {
              text: "电子邮箱",
              id: "email",
              width: 50,
            },
            {
              text: "用户性别",
              id: "sexName",
              width: 50,
            },
            {
              text: "用户生日",
              id: "birthday",
              width: 50,
            },
            {
              text: "用户编号",
              id: "code",
              width: 50,
            },
          ],
        },
      ],
      formObj: {},
      formData: {},
      isShowEdit: false,
      popupList: [
        {
          label: "用户姓名",
          type: "input",
          width: 50,
          value: "",
          id: "username",
        },
        {
          label: "登录账号",
          type: "input",
          width: 50,
          value: "",
          maxlength: 10,
          id: "account",
          disabled: true,
        },
        {
          label: "关联人员",
          width: 50,
          value: "",
          id: "staffId",
          type: "loadselect",
          selectedLabel: "",
          requestObj: {
            url: "/api/trio-user/page",
            method: "get",
            searchKey: "realName",
            rlLabel: "realName/deptName",
            rlValue: "id",
            resultKey: "data,data,records",
          },
        },
        {
          label: "密码",
          type: "input",
          width: 50,
          value: "",
          id: "password",
          autocomplete: "new-password",
          showPassword: true,
          verRule: function (val) {
            const regex = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\W_]).{8,16}$/;
            return regex.test(val);
          },
          verErrorLabel: "密码必须包含字母加数字加特殊字符，长度为8-16位",
        },
        {
          label: "所属角色",
          type: "select",
          width: 50,
          value: [],
          id: "roleIdList",
          list: [],
          multiple: true,
        },
      ],
      totalNum: 0,
      searchParams: {
        staffId: "",
        tenantId: "",
        account: "",
        factoryId: "",
        current: 1,
        size: 10,
      },
      tableData: [],
      searchShowList: [
        {
          label: "登录账号",
          type: "input",
          width: 33.3,
          value: "",
          id: "account",
        },
        {
          label: "组织架构",
          width: 33.3,
          value: "",
          id: "factoryId",
          selectedLabel: "",
          type: "loadselect",
          searchPlaceholder: "请输入",
          requestObj: {
            url: "/api/trio-system/prod-org/page",
            method: "post",
            searchKey: "orgName",
            rlLabel: "orgName",
            rlValue: "id",
            resultKey: "data,data,records",
          },
          defaultParams: {
            orgLevelCode: "FACTORY",
          },
        },
        {
          label: "关联人员",
          id: "staffId",
          type: "loadselect",
          width: 33.3,
          value: "",
          requestObj: {
            url: "/api/trio-user/page",
            method: "get",
            searchKey: "realName",
            rlLabel: "realName",
            rlValue: "id",
            resultKey: "data,data,records",
          },
        },
      ],
      btnList: [
        {
          label: "新增",
          option: "add",
          color: "blue",
        },
        {
          label: "角色配置",
          option: "roleSet",
          color: "white",
          isRelaTable: true,
        },
        {
          label: "密码重置",
          option: "reset",
          color: "white",
          isRelaTable: true,
        },
        {
          label: "删除",
          option: "delete",
          color: "white",
          isRelaTable: true,
        },
      ],
      tableColumn: [
        {
          type: "text",
          label: "登录账号",
          value: "account",
        },
        {
          type: "text",
          label: "用户姓名",
          value: "username",
        },
        // {
        //   type: "text",
        //   label: "隶属企业",
        //   value: "tenantName",
        // },
        {
          type: "text",
          label: "默认组织架构",
          value: "defaultFactoryName",
        },
        {
          type: "text",
          label: "所属角色",
          value: "roleName",
        },
        {
          type: "option",
          label: "操作",
          width: 120,
          showBtnList: [
            {
              label: "组织架构",
              option: "rowGrant",
            },
            {
              label: "编辑",
              option: "rowEdit",
            },

            {
              label: "删除",
              option: "rowDelete",
            },
          ],
        },
      ],
      treeData: [],
      currentHandle: "add",
      defaultFactId: "",
      checkedList: [],
    };
  },
  methods: {
    closePopupHandle() {
      this.$refs.factTable.clearSelect();
      this.isShowGrantPopup = false;
    },
    async confirmFactHandle() {
      if (!this.factIds.length) return this.$message.warning("请选择组织架构");
      if (!this.defaultFactId)
        return this.$message.warning("请选择默认组织架构");
      let params = {
        defaultFactoryId: this.defaultFactId,
        factoryIdList: this.factIds,
        tenantId: this.formData.tenantId,
        userId: this.formData.id,
      };
      let res = await savaFact(params);
      if (res.data.code != 200) return;
      this.$refs.factTable.clearSelect();
      this.$message.success(this.$t("msg.success"));
      this.isShowGrantPopup = false;
      this.getListHandle(this.searchParams);
    },
    changeSwitchHandle(val) {
      if (!val.isDefault) return (this.defaultFactId = "");
      this.defaultFactId = val.id;
      this.grantTableData.forEach((item) => {
        item.isDefault = item.id == this.defaultFactId;
      });
    },
    async getGrantDataHandle() {
      let res = await getTreeList(this.grantSearchParams);
      if (res.data.code != 200) return;
      this.grantTableData = res.data.data.records;
      this.grantTableData.forEach((item) => {
        this.$set(item, "isDefault", item.id == this.defaultFactId);
      });
      this.grantTotal = res.data.data.total;
      this.isShowGrantPopup = true;
    },
    grantHandle(uIds, rIds) {
      grant(uIds, rIds).then((res) => {
        if (res.data.code != 200) return;
        this.isShowEdit = false;
        this.$refs.trTable.clearSelect();
        this.getListHandle(this.searchParams);
        this.$message.success(this.$t("msg.success"));
      });
    },
    addHandle(params) {
      add(params).then((res) => {
        if (res.data.code != 200) return;
        this.formObj = {};
        this.isShowEdit = false;
        this.getListHandle(this.searchParams);
        this.$message.success(this.$t("msg.success"));
      });
    },
    initData() {
      getRoleList({ current: 1, size: 1000, isEnabled: 1 }).then((res) => {
        if (res.data.code != 200) return;
        const column = findByProperty(this.popupList, "id", "roleIdList");
        let list = res.data.data.records.map((item) => {
          return {
            label: item.roleName,
            value: item.id,
          };
        });
        column.list = list;
      });
    },
    confirmHandle(val) {
      console.log(this.formObj, val, "this.formObj");
      if (this.currentHandle == "roleSet") {
        this.grantHandle(this.ids, this.formObj.roleIdList.join(","));
        return;
      }
      if (this.currentHandle == "rowEdit") {
        this.formObj.id = this.formData.id;
        delete this.formObj.password;
      }
      if (this.currentHandle == "add") {
        this.formObj.password = md5(this.formObj.password);
      }
      this.addHandle(this.formObj);
    },
    loadFun(node, resolve) {
      if (node.level === 0) this.getleftTreeHandle(0, resolve);
      return this.getleftTreeHandle(node.data.id, resolve);
    },
    getleftTreeHandle(id, resolve) {
      getDeptLazyTree(id).then((res) => {
        if (resolve) {
          resolve(res.data.data);
        } else {
          this.treeData = res.data.data;
        }
      });
    },
    getListHandle(params) {
      getList(params).then((res) => {
        if (res.data.code != 200) return;
        let data = res.data.data;
        this.$validateData(data);
        this.totalNum = data.total;
        this.tableData = data.records;
        this.tableData.forEach((item) => {
          item.roleName = item.roleList.map((item) => item.roleName).join(",");
        });
      });
    },
    operateHandle(val, type) {
      this.currentHandle = type;
      this.$validateData(val, 3);
      this.defaultFactId = val.defaultFactoryId;
      if (type == "rowEdit" || type == "rowGrant") {
        this.formData = val;
        this.formData.roleIdList = val.roleList.map((item) => item.roleId);
      } else {
        this.formData = {};
      }
      if (type == "roleSet" && !this.ids.includes(",")) {
        this.formData.roleIdList =
          this.$refs.trTable.selectionList[0].roleList.map(
            (item) => item.roleId
          );
      }
      const accountCol = findByProperty(this.popupList, "id", "account");
      accountCol.disabled = type == "rowEdit";
      const roleCol = findByProperty(this.popupList, "id", "roleIdList");
      roleCol.value =
        type == "rowEdit" ? val.roleList.map((item) => item.roleId) : [];
      console.log(this.popupList, "roleCol.value");
      const safCol = findByProperty(this.popupList, "id", "staffId");
      safCol.selectedLabel = type == "rowEdit" ? val.staffName : "";
      switch (type) {
        case "rowDelete": {
          this.$textShow({
            title: this.$t("tip.label"),
            content: [this.$t("tip.delete")],
          })
            .then(async () => {
              let res = await remove(val.id);
              if (res.data.code != 200) return;
              this.$message.success(this.$t("msg.success"));
              this.getListHandle(this.searchParams);
              this.$refs.trTable.clearSelect();
            })
            .catch(() => {});
          return;
        }
        case "delete": {
          this.$textShow({
            title: this.$t("tip.label"),
            content: [this.$t("tip.delete")],
          })
            .then(async () => {
              let res = await remove(this.ids);
              if (res.data.code != 200) return;
              this.$refs.trTable.clearSelect();
              this.$message.success(this.$t("msg.success"));
              this.getListHandle(this.searchParams);
            })
            .catch(() => {});
          return;
        }
        case "reset": {
          this.$textShow({
            title: this.$t("tip.label"),
            content: [this.$t("tip.resetPassWord")],
          })
            .then(async () => {
              let res = await resetPassword(this.ids);
              if (res.data.code != 200) return;
              this.$refs.trTable.clearSelect();
              this.$message.success(this.$t("msg.success"));
              this.getListHandle(this.searchParams);
            })
            .catch(() => {});
          return;
        }
        case "rowGrant": {
          this.checkedList = val.factoryList.map((item) => item.factoryId);
          this.getGrantDataHandle();
          return;
        }
      }
      this.isShowEdit = true;
    },
    searchHandle() {
      this.getListHandle(this.searchParams);
    },
  },
  mounted() {
    // this.getListHandle(this.searchParams);
    this.initData();
  },
};
</script>

<style></style>
